package com.sise.netty.server端和client端通信案例;

import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * @author idea
 * @data 2019/4/15
 */
public class ClientHandle extends SimpleChannelInboundHandler {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("[client] 接收到信息");
        ByteBuf readByteBuf = (ByteBuf) msg;
        byte[] tempDatas = new byte[readByteBuf.readableBytes()];
        String result = new String(tempDatas, "UTF-8");
        System.out.println("from server:" + result);
        //用于释放内存，防止内存溢出
        ReferenceCountUtil.release(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        Channel channel=ctx.channel();
        if(channel.isActive()){
            ctx.close();
        }
    }

}
